//
//  ArrayToDic.m
//  CocoaMoney
//
//  Created by Daniel Braun on 01/10/06.
//  Copyright 2006 Daniel Braun http://braun.daniel.free.fr. All rights reserved.
//

#import "DictionaryWrapper.h"

@implementation DictionaryWrapper 

- (NSString *) description
{
	return [NSString stringWithFormat:@"DictionaryWrapper(k=%@,v=%@)", key, value];
}

- (id) init {
	self = [super init];
	if (self != nil) {
		static int kc=0;
		kc++;
		key=[[NSString stringWithFormat:@"k%d", kc]retain];
		value=@"value";
	}
	return self;
}
- (void) dealloc {
	[key release];
	[value release];
	[super dealloc];
}

- (id)key {
	return [[key retain] autorelease];
}

- (void)setKey:(id)k {
	if (key != k) {
		[key release];
		key = [k retain];
	}
}

- (NSString *) stringValue
{
	NSString *s=[NSString stringWithFormat:@"(%@)", value ];
	return s;
}

- (id)value {
	return value;
}

- (void)setValue:(id)v {
	if (value != v) {
		[value release];
		value = [v retain];
	}
}



- (id) val
{
	return value;
}
- (void) setVal:(id)v
{
	[self setValue:v];
}


- (void)encodeWithCoder:(NSCoder *)coder
{
	//[super encodeWithCoder:coder];
	if ( [coder allowsKeyedCoding] ) {
		[coder encodeObject:key forKey:@"key"];
		[coder encodeObject:value forKey:@"value"];
	} else {
		NSAssert(0, @"only key coder supported\n");
	}
}
- (id) initWithCoder:(NSCoder *) coder
{
	//self=[super initWithCoder:coder];
	self=[super init];
	if ([coder allowsKeyedCoding]) {
		key=[[coder decodeObjectForKey:@"key"]retain];
		value=[[coder decodeObjectForKey:@"value"]retain];
	}
	return self;
}

- (NSString *) vclassName
{
	return [value className];
}

+ (NSMutableArray *) arrayFromDictionary:(NSDictionary *)dic
{
	NSMutableArray *array=[NSMutableArray arrayWithCapacity:[dic count]];
	NSEnumerator *ke;
	ke=[dic keyEnumerator];
	for (;;) {
		id key, value;
		DictionaryWrapper *item;
		key=[ke nextObject];
		if (!key) break;
		NSAssert([key isKindOfClass:[NSString class]], @"strange, key is not string"); // to be removed
		value=[dic objectForKey:key];
		item=[[DictionaryWrapper alloc] init];
		[item setKey:key];
		[item setValue:value];
		[array addObject:item];
		[item release];
	}
	return array;
}

+ (NSMutableDictionary *) dictionaryFromArray:(NSArray *)array
{
	unsigned int i, count = [array count];
	NSMutableDictionary *dic=[NSMutableDictionary dictionaryWithCapacity:count];
	for (i = 0; i < count; i++) {
		DictionaryWrapper * dv = [array objectAtIndex:i];
		NSAssert([dv isKindOfClass:[DictionaryWrapper class]], @"bad element class");
		[dic setObject:[dv value] forKey:[dv key]];
	}
	return dic;
}


@end
